<?php

namespace App\Lib\Niutrans;

use Swlib\Saber;
use Swlib\Http\Exception\RequestException;

class Xunfei
{
    // 机器翻译接口地址
    protected $url = 'https://ntrans.xfyun.cn/v2/ots';
    protected $requestLine = 'POST /v2/ots HTTP/1.1';
    protected $accept = 'application/json,version=1.0';
    protected $contentType = 'application/json';
    protected $headers = 'host date request-line digest';
    protected $host = 'ntrans.xfyun.cn';
    //在控制台-我的应用-机器翻译获取
    protected $apiId = '5f6b0f78';
    //在控制台-我的应用-机器翻译获取
    protected $apiSec = '7794ce60b981fa32175e9b1bb7ebb23f';
    //在控制台-我的应用-机器翻译获取
    protected $apiKey = 'eeb9fde124a71e0e4b266f44469ed165';

    public function __construct($config = [])
    {
        $this->apiId = $config['apiId'] ?? $this->apiId;
        $this->apiSec = $config['apiSec'] ?? $this->apiSec;
        $this->apiKey = $config['apiKey'] ?? $this->apiKey;
    }

    public function xfyun($data)
    {
        $body = json_encode($this->getBody($this->apiId, $data['from'] ?? 'auto', $data['to'], $data['text']));

        // 组装http请求头
        $date = $this->getDate();
        $digestBase64  = "SHA-256=".base64_encode($this->makeSign($body));
        $builder = sprintf("host: %s\ndate: %s\n%s\ndigest: %s", $this->host, $date, $this->requestLine, $digestBase64);
        // echo($builder);
        $sha = base64_encode($this->hashEncode($builder));

        $authorization = sprintf(
            "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",
            $this->apiKey,
            "hmac-sha256",
            $this->headers,
            $sha
        );

        $header = [
            'Authorization' => $authorization,
            'Content-Type' => $this->contentType,
            'Accept' => $this->accept,
            'Host' => $this->host,
            'Date' => $date,
            'Digest' => $digestBase64
        ];
        try {
            $saber = Saber::create([
                'headers' => $header
            ]);
            $response = $saber->post($this->url, $body)->getBody();
            $res = \json_decode((string)$response, true);
            $res['errorCode'] = $res['code'];
            return $res;
        } catch (RequestException $e) {
            return ['errorCode' => $e->getCode(), 'data' => $e->getMessage()];
        }
    }
    //加密
    public function hashEncode($builder)
    {
        return hash_hmac("sha256", $builder, $this->apiSec, true);
    }
    //生成Digest
    public function makeSign($body)
    {
        return hash("sha256", $body, true);
    }
    //获取时间
    public function getDate()
    {
        return gmdate('D, d M Y H:i:s') . ' GMT';
    }
    //组装请求数据
    public function getBody($app_id, $from, $to, $text)
    {
        $common_param = [
            'app_id'   => $app_id
        ];
        $business = [
            'from' => $from,
            'to'   => $to,
        ];
        $data = [
            "text" => base64_encode($text)
        ];
        return $body = [
            'common' => $common_param,
            'business' => $business,
            'data' => $data
        ];
    }
}
